import React, { useEffect, useImperativeHandle, useState } from "react";

import { BoxShadow } from "../../styles/common";
import styled from "styled-components";

const Wrap = styled(BoxShadow)`
  display: flex;
  flex-direction: column;
`;

const HeaderWrap = styled(BoxShadow)`
  font-size: 18px;
  padding: 10px 0 0;
  text-transform: capitalize;
  display: flex;
  flex-direction: row;
`;

// 对应过滤掉的属性，在取值时同样需要使用 $
const HeaderItem = styled.div`
  padding-bottom: 10px;
  background-color: white;
  width: ${(props) => props.$width};
  text-align: center;
  border-bottom: 3px solid ${(props) => (props.$active ? "red" : "white")};
`;

const ContentWrap = styled.div`
  font-size: 14px;
  padding: 10px;
`;

const ContentItem = styled.div``;

const Tab = ({ data, onChange }, ref) => {
  const [activeIndex, setActiveIndex] = useState(0);

  useEffect(() => {
    onChange && onChange({ last: activeIndex, active: activeIndex });
  }, []);

  useImperativeHandle(ref, () => ({
    setActiveIndex,
  }));

  const handleHeadClick = (index) => {
    onChange && onChange({ last: activeIndex, active: index });
    setActiveIndex(index);
  };

  const buildHeader = (item, index, count) => {
    const { key, title } = item;

    return (
      <HeaderItem
        $active={index === activeIndex} // 对于你不希望传递给 DOM 元素的 prop，你可以在 prop 名称前加上 $ 符号
        $width={`${100 / count}%`}
        key={`header${key}`}
        onClick={() => handleHeadClick(index)}
      >
        {title}
      </HeaderItem>
    );
  };

  const buildContent = (item) => {
    const { key, content } = item;
    return <ContentItem key={`content${key}`}>{content}</ContentItem>;
  };

  const buildTabDom = () => {
    const headersDom = [];
    const contentsDom = [];
    data.forEach((item, index) => {
      headersDom.push(buildHeader(item, index, data.length));
      contentsDom.push(buildContent(item));
    });

    return (
      <>
        <HeaderWrap>{headersDom}</HeaderWrap>
        <ContentWrap>{contentsDom[activeIndex]}</ContentWrap>
      </>
    );
  };

  return <Wrap>{buildTabDom()}</Wrap>;
};

export default React.forwardRef(Tab);
